package com.liwy3.lark;

import com.liwy3.*;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;

import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;

/**
 * 飞书API: https://open.feishu.cn/document/ukTMukTMukTM/uITNz4iM1MjLyUzM
 */
@Accessors(chain = true)
@Slf4j
@Data
public class Lark {

    private String appName;
    private String appId;
    private String appSecret;
    private String alertPrefix = "";

    private LarkToken access_token;
    private LarkToken tenant_token;

    public String createClientAuthURL(String client) {
        String domain = "https://scm.yuanqisenlin.com";
        String url = String.format("%s/index/lark/%s/%s", domain, appName, client);
        return createAuthURL(url);
    }

    public String createAuthURL(String redirectURL) {
        return String.format("https://open.feishu.cn/open-apis/authen/v1/index?redirect_uri=%s&app_id=%s",
                YQException.runtime(() -> URLEncoder.encode(redirectURL, "UTF-8")), appId);
    }

    public LarkToken getTenantToken() {
        Date now = new Date();
        if (tenant_token == null || tenant_token.getExpireTime().before(now)) {
            YQHttp.Response resp = YQHttp.newRequest()
                    .setUrl("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/")
                    .addParameter("app_id", appId)
                    .addParameter("app_secret", appSecret)
                    .json();
            LarkToken token = YQJsonUtils.toObject(resp.getContent(), LarkToken.class);
            if (token.getCode() != 0) {
                throw new RuntimeException(resp.getContent());
            }
            token.expireTime = (DateUtils.addSeconds(now, token.expire - 600)); // 提前10分钟失效
            tenant_token = token;
        }
        return tenant_token;
    }

    private LarkToken getAccessToken() {
        Date now = new Date();
        if (access_token == null || access_token.getExpireTime().before(now)) {
            YQHttp.Response resp = YQHttp.newRequest()
                    .setUrl("https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal/")
                    .addParameter("app_id", appId)
                    .addParameter("app_secret", appSecret)
                    .json();
            LarkToken token = YQJsonUtils.toObject(resp.getContent(), LarkToken.class);
            if (token.getCode() != 0) {
                throw new RuntimeException(resp.getContent());
            }
            token.expireTime = (DateUtils.addSeconds(now, token.expire - 600)); // 提前10分钟失效
            access_token = token;
        }
        return access_token;
    }

    public LarkUser getLarkUser(String code) {
        YQHttp.Response resp = YQHttp.newRequest()
                .setUrl("https://open.feishu.cn/open-apis/authen/v1/access_token")
                .addParameter("app_access_token", getAccessToken().getApp_access_token())
                .addParameter("grant_type", "authorization_code")
                .addParameter("code", code)
                .json();
        log.info("查询用户信息 {}", resp.getContent());

        YQMap data = YQJsonUtils.toObject(resp.getContent(), YQMap.class);
        if (data.getInteger("code") != 0) {
            throw new RuntimeException("获取飞书用户信息失败: " + resp.getContent());
        }

        return YQJsonUtils.toObject(YQJsonUtils.toJson(data.getMap("data")), LarkUser.class);
    }

    public LarkUser getLarkUserByAccessToken(String userAccessToken) {
        YQHttp.Response resp = YQHttp.newRequest()
                .setUrl("https://open.feishu.cn/open-apis/authen/v1/user_info")
                .addHeader("Authorization", "Bearer " + userAccessToken)
                .addParameter("user_access_token", userAccessToken)
                .get();
        log.info("查询用户信息 {}", resp.getContent());

        YQMap data = YQJsonUtils.toObject(resp.getContent(), YQMap.class);
        if (data.getInteger("code") != 0) {
            throw new RuntimeException("获取飞书用户信息失败: " + resp.getContent());
        }

        return YQJsonUtils.toObject(YQJsonUtils.toJson(data.getMap("data")), LarkUser.class);
    }

    public void send(String larkUserId, String title, List<LarkMsg> items) {
        Map content = new HashMap<>();

//        Map post = new HashMap<>();
//        content.put("post", post);
//
//        Map zh_cn = new HashMap<>();
//        post.put("zh_cn", zh_cn);
//        zh_cn.put("title", title);
//
//        zh_cn.put("content", Arrays.asList(items));


        String resp = YQHttp.newRequest().setUrl("https://open.feishu.cn/open-apis/message/v4/send/")
                .addHeader("Authorization", "Bearer " + getTenantToken().getTenant_access_token())
                .addParameter("user_id", larkUserId)
                .addParameter("msg_type", "post")
                .addParameter("content", content)
                .json().getContent();

        log.info("发送飞书消息结果: {}", resp);
        YQMap data = YQJsonUtils.toObject(resp, YQMap.class);
        if (data.getInteger("code") != 0) {
            throw new RuntimeException("发送飞书消息失败: " + resp);
        }
    }

    @Data
    public static class LarkToken {
        private int code;
        private String app_access_token;
        private int expire;
        private String tenant_access_token;
        private Date expireTime;
    }

}
